﻿using Devil;
using LitJson;
using System.Text;
using UnityEditor;
using UnityEditor.AssetImporters;
using UnityEditor.Callbacks;

namespace GameToolkit.Editor
{
    [ScriptedImporter(1, "storygraph")]
    public class StoryGraphAssetImporter : JsonAssetImpoter<TaskGraphAsset>
    {
        [MenuItem("CONTEXT/TaskGraphAsset/Save As")]
        static void ExportAsset(MenuCommand cmd)
        {
            var ai = cmd.context as TaskGraphAsset;
            if (ai != null)
            {
                var file = EditorUtility.SaveFilePanelInProject("Save StoryGraph As", $"{ai.name}_copy", "storygraph", "Save story graph asset.");
                if (string.IsNullOrEmpty(file))
                    return;
                var json = JsonSerializedObject.ExportFrom(ai);
                if (json == null)
                    return;
                NativeFileSystem.WriteAllText(file, JsonMapper.ToJson(json), Encoding.UTF8);
                AssetDatabase.ImportAsset(file);
            }
        }

        [MenuItem("CONTEXT/TaskGraphAsset/Open With New Editor")]
        static void OpenAsset(MenuCommand cmd)
        {
            var ai = cmd.context as TaskGraphAsset;
            if (ai != null)
                StoryGraphEditor.OpenAsset(ai, true);
        }

        [OnOpenAsset(OnOpenAssetAttributeMode.Execute)]
        static bool OpenAsset(int instanceID, int line)
        {
            var inst = EditorUtility.InstanceIDToObject(instanceID) as TaskGraphAsset;
            if (inst == null)
                return false;
            StoryGraphEditor.OpenAsset(inst, false);
            return true;
        }

    }
}
